package com.xiaomi.controller;

import com.xiaomi.constant.MessageConstant;
import com.xiaomi.dto.SignalDTO;
import com.xiaomi.result.Result;
import com.xiaomi.service.SignalService;
import com.xiaomi.vo.SignalVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/signal")
public class SignalController {
    @Autowired
    private SignalService signalService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 添加信号
     * @param signalDTO
     * @return
     */
    @PostMapping("/addSignal")
    public Result add(@RequestBody SignalDTO signalDTO){
        log.info("添加信号，参数：{}",signalDTO);
        signalService.add(signalDTO);
        return Result.success(MessageConstant.ADD_SIGNAL_SUCCESS);
    }

    /**
     * 根据信号id获取信号
     * @param id
     * @return
     */
    @GetMapping("/getSignalById/{id}")
    public Result<SignalVO> getSignalById(@PathVariable Integer id){
        log.info("根据id获取信号，参数：{}",id);
        SignalVO signalVO = signalService.getSignalById(id);
        return Result.success(MessageConstant.GET_SIGNAL_SUCCESS,signalVO);
    }

    /**
     * 根据车架ID获取当前车架的最新信息
     * @param carFrameNumber
     * @return
     */
    @GetMapping("/getSignalsByCarFrameNumber/{carFrameNumber}")
    public Result<SignalVO> getSignalsByCarFrameNumber(@PathVariable Long carFrameNumber) {
        log.info("根据车架ID获取当前车架的所有信息，参数：{}", carFrameNumber);
        SignalVO signalVO = signalService.getSignalsByCarFrameNumber(carFrameNumber);
        if (signalVO == null) {
            return Result.error(0,MessageConstant.SIGNAL_NOT_FOUND);
        }
        return Result.success(MessageConstant.GET_SIGNALS_BY_CAR_FRAME_NUMBER_SUCCESS, signalVO);
    }
    /**
     * 文件上传
     * @return
     */
    @PostMapping("/upload")
    public Result upload(
            @RequestPart("excelFile") MultipartFile file) {

        log.info("收到文件上传请求，文件名：{}", file.getOriginalFilename());

        // 参数校验
        if (file == null) {
            log.error("文件参数绑定失败");
            return Result.error(0, "请选择上传文件");
        }
        if (file.isEmpty()) {
            return Result.error(0, "上传文件不能为空");
        }
        if (!"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                .equals(file.getContentType())) {
            return Result.error(0, "仅支持.xlsx格式文件");
        }

        // 处理业务逻辑
        try {
            signalService.processExcel(file.getInputStream());
            return Result.success( "信息上传成功");
        } catch (IOException e) {
            log.error("文件流处理异常", e);
            return Result.error(0, "文件处理失败");
        }
    }

}
